package com.example.tms.controller;

import com.example.tms.bean.CarInfo;
import com.example.tms.bean.OilcardMgmt;
import com.example.tms.bean.OilfillInfo;
import com.example.tms.bean.ReturnInfo;
import com.example.tms.mapper.OilcardMapper;
import com.example.tms.tools.GlobalParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.example.tms.annotation.*;

/**
 * 油卡管理
 */
@RestController
public class OilcardController {

    private final OilcardMapper oilcardMapper;

    @Autowired
    public OilcardController(OilcardMapper oilcardMapper) {
        this.oilcardMapper = oilcardMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //查询油卡信息列表
    @RequiresPermissions("411")
    @RequestMapping(value = "oilcard",method = RequestMethod.GET)
    public ReturnInfo getOilcardMgmtAll(@RequestParam(required = false, defaultValue = "") String ykh,
                                       @RequestParam(required = false, defaultValue = "") String jyz,
                                       @RequestParam(required = false, defaultValue = "") String yklb){
        List<OilcardMgmt> result = oilcardMapper.findAll((Root<OilcardMgmt> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if(!ykh.equals("")){
                list.add(criteriaBuilder.like(root.get("ykh").as(String.class),"%" + ykh + "%"));
            }
            if(!jyz.equals("")){
                list.add(criteriaBuilder.like(root.get("jyz").as(String.class),"%" + jyz + "%"));
            }
            if(!yklb.equals("")){
                list.add(criteriaBuilder.like(root.get("yklb").as(String.class),"%" + yklb + "%"));
            }
            list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class),true));
            Predicate[] p = new Predicate[list.size()];
            criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("lasttime")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
    }

    //查询油卡信息
    @RequiresPermissions("411")
    @RequestMapping(value = "oilcard/{ykid}",method = RequestMethod.GET)
    public OilcardMgmt getOilcardMgmt(@PathVariable String ykid){
        return oilcardMapper.findByYkid(ykid);
    }

    //查询油卡列表
    @RequestMapping(value = "oilcardlist",method = RequestMethod.GET)
    public ReturnInfo getCarList(){
        List<OilcardMgmt> oilcardMgmts = oilcardMapper.findBySfczOrderByLasttimeAsc(true);
        List<OilcardMgmt> oilcardLists = new ArrayList<>();
        for(OilcardMgmt oilcardMgmt : oilcardMgmts){
            oilcardLists.add(new OilcardMgmt(oilcardMgmt.getYkid(),oilcardMgmt.getYkh()));
        }
        return ReturnInfo.info2(oilcardLists);
    }

    //新建油卡信息
    @MonitorRequest
    @RequiresPermissions("412")
    @RequestMapping(value = "oilcard",method = RequestMethod.POST)
    public List<Map<String,Object>> saveOilcardMgmt(@RequestBody OilcardMgmt oilcardMgmt){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(oilcardMgmt.getYkh().equals("")){
            map.put("ykh","0");
        }else if(oilcardMapper.findByYkh(oilcardMgmt.getYkh())!=null){
            map.put("ykh","2");
        }
        list.add(map);
        if(map.isEmpty()){
            oilcardMgmt.setLasttime(GlobalParam.getTime());
            oilcardMgmt.setSfcz(true);
          //  oilcardMgmt.setDqye(mul(oilcardMgmt.getCsje(),oilcardMgmt.getLjczje(),oilcardMgmt.getLjsjcyje()));
            oilcardMapper.save(oilcardMgmt);
            logger.info("新建油卡"+oilcardMgmt.toString());
        }
        return list;
    }

    //更新油卡信息
    @MonitorRequest
    @RequiresPermissions("413")
    @RequestMapping(value = "oilcard",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateOilcardMgmt(@RequestBody OilcardMgmt oilcardMgmt){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(oilcardMgmt.getYkid().equals("")||oilcardMapper.findByYkid(oilcardMgmt.getYkid())==null){
            map.put("ykid", "0");
        }
        OilcardMgmt oldcard = oilcardMapper.findByYkid(oilcardMgmt.getYkid());
        if(oldcard!=null&&!oilcardMgmt.getYkh().equals(oldcard.getYkh())&&oilcardMapper.findByYkh(oilcardMgmt.getYkh())!=null) {
            map.put("ykh", "2");
        }
        list.add(map);
        if(map.isEmpty()){
            oilcardMgmt.setLasttime(GlobalParam.getTime());
            oilcardMgmt.setSfcz(true);
           // oilcardMgmt.setDqye(mul(oilcardMgmt.getCsje(),oilcardMgmt.getLjczje(),oilcardMgmt.getLjsjcyje()));
            oilcardMapper.saveAndFlush(oilcardMgmt);
            logger.info("更新油卡"+oilcardMgmt.toString());
        }
        return list;
    }

    //删除油卡信息（假删除 油卡id）
    @MonitorRequest
    @RequiresPermissions("414")
    @RequestMapping(value = "oilcard/{ykid}",method = RequestMethod.DELETE)
    public ReturnInfo deleteOilcardMgmt(@PathVariable String  ykid){
        String b;
        if(oilcardMapper.findByYkid(ykid)==null){
            b = "删除失败！";
        }else{
            oilcardMapper.DeleteByYkid(ykid);
            b = "删除成功！";
            logger.info("删除油卡"+ykid);
        }
        return ReturnInfo.info1(b);
    }

    //计算当前余额
    private String mul(String csje, String ljczje, String ljsjcyje){
        String dqye = "";
        if(!csje.equals("")&&!ljczje.equals("")&&!ljsjcyje.equals("")){
            BigDecimal b1 = new BigDecimal(csje);
            BigDecimal b2 = new BigDecimal(ljczje);
            BigDecimal b3 = new BigDecimal(ljsjcyje);
            dqye = b1.add(b2).subtract(b3).toString();
        }
        return dqye;
    }
}
